package com.example.friend.service.question.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.domin.TableDataInfo;
import com.example.friend.domain.question.Question;
import com.example.friend.domain.question.dto.QuestionQueryDTO;
import com.example.friend.domain.question.es.QuestionES;
import com.example.friend.domain.question.vo.QuestionDetailVO;
import com.example.friend.domain.question.vo.QuestionVO;
import com.example.friend.elasticsearch.QuestionRepository;
import com.example.friend.manager.QuestionCacheManager;
import com.example.friend.mapper.question.QuestionMapper;
import com.example.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    //题目列表
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        //先查询es有无数据
        long count = questionRepository.count();
        if (count <= 0) {
            //将数据库中的数据同步到es中
            refreshQuestion();
        }
        //排序逻辑
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //分页参数处理和排序一下 pageNum是从0开始的
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(),sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if(difficulty == null && StrUtil.isEmpty(keyword)){
            //全查
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            //只传了难度
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            //只传模糊查询参数
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            //都传
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        //总数据量
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        //获取查询到的数据
        List<QuestionES> questionESList = questionESPage.getContent();
        //前端题目列表不需要展示太多数据,这里将返回的数据删减一些
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    //查询题目详情
    @Override
    public QuestionDetailVO detail(Long questionId) {
        //先从es上进行查询 --- orElse处理查询不到的情况(这块就是直接返回空)
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        //es上能直接查询的到就直接返回
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        //从数据库中查
        Question question = questionMapper.selectById(questionId);
        if(question == null){
            return null;
        }
        //刷新es
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    //上一题
    @Override
    public String preQuestion(Long questionId) {
        checkAndRefresh();
        return questionCacheManager.preQuestion(questionId).toString();
    }

    //下一题
    @Override
    public String nextQuestion(Long questionId) {
        checkAndRefresh();
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    //检查redis中,题目顺序列表
    public void checkAndRefresh() {
        //先判断redis中是否有数据
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            //刷新缓存
            questionCacheManager.refreshCache();
        }
    }



    private void refreshQuestion() {
        //同步全部数据,不需要加查询条件
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)) {
            return;
        }
        //类型转换
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        //同步es
        questionRepository.saveAll(questionESList);
    }
}
